﻿using SoldiHive.Core.Adapters;
using SoldiHive.Model;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace SoldiHive.Core.Crawlers
{
	public class RatingsCrawler : IRatingsCrawler
	{
		private ICurrentPriceAdapter currentPriceAdapter;
		private IList<IRatingsAdapter> ratingsAdapters;
		private IRatingsCrawlerConfiguration config;

		public RatingsCrawler(IList<IRatingsAdapter> ratingsAdapters, ICurrentPriceAdapter currentPriceAdapter, IRatingsCrawlerConfiguration config)
		{
			this.ratingsAdapters = new List<IRatingsAdapter>(ratingsAdapters);
			this.currentPriceAdapter = currentPriceAdapter;
			this.config = config;
		}

		public IList<Rating> GetRatings(Company company)
		{
			var ratings = new List<Rating>();
			Parallel.ForEach(this.ratingsAdapters, (ratingsAdapter) =>
			{
				Rating rating = null;

				var retriesCount = config.RetriesCount;
				var retriesDelay = config.RetriesDelaysMilliseconds;

				while (retriesCount-- > 0 && rating == null)
				{
					Thread.Sleep(retriesDelay);
					rating = ratingsAdapter.GetRating(company);
				}

				if (rating == null)
				{
					rating = new Rating(ratingsAdapter.Source);
				}

				ratings.Add(rating);
			});

			return ratings;
		}
	}
}
